from flask import Flask, request, jsonify
from flask_cors import CORS
from util.JsonWebToken import Jwt

app = Flask(__name__)
CORS(app)
key = "as3&b3we%f845.6"  # JWT 密钥


@app.route('/login', methods=['POST'])
def login():
    data = request.json
    username = data.get('username')

    access_token = Jwt.encode({'username': username, "type": "access_token"}, key, 30)
    refresh_token = Jwt.encode({'username': username, "type": "refresh_token"}, key, 86400)
    return jsonify(
        {
            'code': 200,
            'msg': 'login success',
            'data': {
                'access_token': access_token,
                'refresh_token': refresh_token
            }
        }
    )


@app.route('/refresh')
def refresh():
    refresh_token = request.args.get("refresh_token")
    if refresh_token is None:
        return jsonify({'code': 401, 'msg': 'refresh_token无效'})
    try:
        payload = Jwt.decode(refresh_token, key)
        if payload['type'] != 'refresh_token':
            return jsonify({'code': 401, 'msg': 'refresh_token无效'})
        payload["type"] = "access_token"
        access_token = Jwt.encode(payload, key, 30)
        return jsonify({
            'code': 200,
            'msg': 'refresh success',
            'data': {
                'access_token': access_token
            }
        })
    except:
        return jsonify({'code': 401, 'msg': 'refresh_token无效'})


@app.route('/test')
def test():
    token = request.headers.get('Authorization')
    if token is None:
        return jsonify({'code': 401, 'msg': 'access_token无效'})
    try:
        access_token = token.split(' ')[1]
        payload = Jwt.decode(access_token, key)
        if payload['type'] != 'access_token':
            return jsonify({'code': 401, 'msg': 'access_token无效'})
        return jsonify({'code': 200, 'msg': 'test success'})
    except:
        return jsonify({'code': 401, 'msg': 'access_token无效'})


if __name__ == '__main__':
    app.run()
